<template>
  <div ref="chart" class="chart" :style="{ height: '400px' }"></div>
</template>

<script setup>
import {onMounted, ref, onBeforeUnmount} from 'vue';
import * as echarts from 'echarts';
import {getAllCategory} from "@/apis/course.js";

// 提供的数据
const categoriesData = ref([]); // 将 categoriesData 定义为 ref

const AllCategory = async () => {
  const res = await getAllCategory();
  categoriesData.value = res.data;
}

const chart = ref(null);
let myChart = null;

const initChart = () => {
  myChart = echarts.init(chart.value);

  // 提取类别名称
  const categories = categoriesData.value.map(category => category.categoryName);
  // 假设每个类别的数量为1
  const values = categoriesData.value.map(() => 1);

  const options = {
    title: {
      text: '课程分类占比',
      left: 'center',
      top: '20px',
      textStyle: {
        fontSize: 24,
        fontWeight: 'bold',
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: categories
    },
    series: [
      {
        name: '课程类别',
        type: 'pie',
        radius: '50%',
        data: categoriesData.value.map((category, index) => ({
          value: values[index],
          name: category.categoryName
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        itemStyle: {
          color: (params) => {
            const colors = ['#4B9CD3', '#F39C12']; // 可以根据需要增加颜色
            return colors[params.dataIndex % colors.length];
          }
        }
      }
    ]
  };

  myChart.setOption(options);
};

onMounted(async () => {
  await AllCategory(); // 等待分类数据加载完成
  initChart(); // 然后初始化图表

  // 监听窗口变化
  window.addEventListener('resize', myChart.resize);
});

onBeforeUnmount(() => {
  // 销毁图表实例
  myChart.dispose();
});
</script>

<style scoped>
.chart {
  width: 100%;
}
</style>
